<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{padding: 0px;
        margin: 0px;
            }
        body{
            width: 100vw;
            height: 100vh;
            position: relative;
        }
        .a1{
            width: 100px;
            height: 100px;
            background-color: orange;
            position: absolute;
            top: 0px;left: 0px;
        }
    </style>
</head>
<body>
    <div class="a1"></div>
</body>
<script>
    var a1=document.getElementsByClassName("a1")[0];
    a1.addEventListener("mousedown",function(e1){
        var startX=e1.offsetX;
        var startY=e1.offsetY;
        startX-=0.5*a1.clientWidth;
        startY-=0.5*a1.clientHeight;
          //自动居中,用上左边距和开始距离完成
          a1.style.top=a1.offsetTop+startY+"px"
          a1.style.left=a1.offsetLeft+startX+"px"//对齐中点
        a1.addEventListener("mousemove",mousemove);
        document.body.addEventListener("mouseup",mouseup);
        function mouseup(){
            a1.removeEventListener("mousemove",mousemove)
        }
        function mousemove(e2){
           var moveX=e2.offsetX-0.5*a1.clientWidth;;//直接元素内部计算就行,用
           var moveY=e2.offsetY-0.5*a1.clientHeight;
           console.log(moveX,moveY)
           a1.style.top=a1.offsetTop+moveY+"px";
          a1.style.left=a1.offsetLeft+moveX+"px";
        }
    },false)
</script>
</html>